package Web;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/WebRtcWSServer")
public class WebRtcWServer {
    private static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session) {
        String queryString = session.getQueryString();
        String username = extractUsernameFromQueryString(queryString);
        if (username != null) {
            sessionMap.put(username, session);
            System.out.println("WebSocket opened for user: " + username);
        } else {
            System.out.println("Invalid username parameter in the query string");
        }
    }
    public static  String extractUsernameFromQueryString(String queryString) {
        if (queryString != null && queryString.contains("username=")) {
            String[] parts = queryString.split("=");
            if (parts.length == 2) {
                return parts[1];
            }
        }
        return null;
    }
    @OnClose
    public void onClose(Session session) {
        for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
            if (entry.getValue() == session) {
                String queryString = session.getQueryString();
                String username = extractUsernameFromQueryString(queryString);
                System.out.println(username+"--->already_offline");
                sessionMap.remove(entry.getKey());
                break;
            }
        }
    }
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            HashMap hashMap = mapper.readValue(message, HashMap.class);
            String type = (String) hashMap.get("type");
            String toUser = (String) hashMap.get("toUser");
            Session toUserSession = sessionMap.get(toUser);
            String fromUser = (String) hashMap.get("fromUser");
            String msg = (String) hashMap.get("msg");
            String sdp = (String) hashMap.get("sdp");
            Map iceCandidate  = (Map) hashMap.get("iceCandidate");
            HashMap<String, Object> map = new HashMap<>();
            map.put("type",type);
            if(toUserSession == null){
                toUserSession = session;
                map.put("type","call_back");
                map.put("fromUser","系统消息");
                map.put("msg","Sorry，呼叫的用户不在线！");
                send(toUserSession,mapper.writeValueAsString(map));
                return;
            }
            if ("hangup".equals(type)) {
                map.put("fromUser",fromUser);
                map.put("msg","对方挂断！");
            }
            if ("call_start".equals(type)) {
                map.put("fromUser",fromUser);
                map.put("msg","1");
            }
            if ("call_back".equals(type)) {
                map.put("fromUser",toUser);
                map.put("msg",msg);
            }
            if ("offer".equals(type)) {
                map.put("fromUser",toUser);
                map.put("sdp",sdp);
            }
            if ("answer".equals(type)) {
                map.put("fromUser",toUser);
                map.put("sdp",sdp);
            }
            if ("_ice".equals(type)) {
                map.put("fromUser", toUser);
                map.put("sdpMid", hashMap.get("sdpMid"));
                map.put("sdpMLineIndex", hashMap.get("sdpMLineIndex"));
                map.put("candidate", hashMap.get("candidate"));
            }
            send(toUserSession,mapper.writeValueAsString(map));
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    private void send(Session session, String message) {
        try {
            System.out.println(message);
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            System.out.println("服务器异常send");
        }
    }
}